import { useEffect, useState, useRef, useMemo, useCallback } from 'react'
import { useOutletContext, useLocation } from 'react-router-dom' //获取路由的上下文
import useIsMobile from '@/hooks/isMoboile' //判断是否是移动端
import AiPersonCard from './Components/AiPersonCard' // 人设卡片
import { useHomeData } from '@/hooks/useHomeData' //获取数据
import { AIPerson } from '@/types/index'
import { useTranslation } from 'react-i18next'
import CollapsePanel from './Components/CollapsePanel' // 折叠面板
import TabRichContent from './Components/TabRichContent' //富文本区域
import PromotionCard from './Components/PromotionCard' // 广告卡片
import { useNavigate } from 'react-router-dom';
import { getDynamicFonts } from '@/utils/fontUtils';
import RegistrationSuccessModal from '@/components/RegistrationSuccessModal'; // Import the modal

export default function Home() {
  const { activeTab } = useOutletContext<{ activeTab: string }>()
  const isMobile = useIsMobile() // 引入isMobile判断
  const { t, i18n } = useTranslation();
  const dynamicFonts = getDynamicFonts(i18n);
  const [showLoading, setShowLoading] = useState(false); // 延迟loading显示，避免闪烁
  const [showRegistrationSuccess, setShowRegistrationSuccess] = useState(false); // State for showing registration success modal
  const location = useLocation();
  // 🔧 新增：用于管理scrollToAiCard中setTimeout的ref，防止内存泄漏
  const scrollTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const highlightTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const {
    data,
    loading,
    hasMore,
    totalPages,
    // checkingTotal,
    page,
    setPage
  } = useHomeData(activeTab, i18n.language)// 使用自定义hook管理数据
  const navigate = useNavigate(); // 引入useNavigate页面跳转
  const isFirstMount = useRef(true); // 标记是否为首次挂载

  // Check if user just registered successfully
  useEffect(() => {
    // Check URL params first
    const urlParams = new URLSearchParams(location.search);
    const justRegistered = urlParams.get('registration') === 'success';
    
    // Also check localStorage as an alternative way to detect registration
    const registrationFlag = localStorage.getItem('just_registered');
    
    if (justRegistered || registrationFlag === 'true') {
      setShowRegistrationSuccess(true);
      
      // Clean up URL if needed
      if (justRegistered) {
        const cleanUrl = window.location.pathname;
        window.history.replaceState({}, document.title, cleanUrl);
      }
      
      // Clean up localStorage flag
      if (registrationFlag) {
        localStorage.removeItem('just_registered');
      }
    }
  }, [location]);

  // Handle closing the registration success modal
  const handleCloseRegistrationModal = () => {
    setShowRegistrationSuccess(false);
  };

  // 🚀 性能优化：使用useMemo缓存数据转换结果，避免每次渲染都重新计算
  const transformedData = useMemo(() => {
    return data.map((item: any) => {
      // 数据转换：将API数据格式转换为AIPerson格式
      const aiPersonData: AIPerson = {
        id: item.id,
        username: item.username || item.information?.name || '',
        avatar: item.avatar || '',
        image: item.image || '', // 使用avatar作为主图片
        videos: item.videos || [],
        age: item.age || item.information?.age || 0,
        description: item.description || '',
        isPremium: item.isPremium || item.is_premium || false,
        likes: typeof item.likes === 'string' ? parseInt(item.likes) || 0 : item.likes || 0,
        comments: typeof item.comments === 'string' ? parseInt(item.comments) || 0 : item.comments || 0,
        character_profile: {
          basic_info: {
            age: item.age || item.information?.age || 0
          },
          videos: item.videos || [],
          ...item.character_profile
        }
      };
      return aiPersonData;
    });
  }, [data]); // 只有当data变化时才重新计算

  // 🚀 性能优化：使用useCallback缓存点击处理函数
  const handleCardClick = useCallback((id: string | number) => {
    // 保存点击的AI角色ID，用于返回时滚动定位
    sessionStorage.setItem('lastClickedAiId', String(id));
    sessionStorage.setItem('returnFromChat', 'true');
    // 保存当前对话ID到sessionStorage
    sessionStorage.setItem('currentConversationId', String(id));
    navigate('/conversation');
  }, [navigate]);

  // 🚀 性能优化：使用useMemo缓存包含广告卡片的渲染列表
  const renderCards = useMemo(() => {
    const cards: JSX.Element[] = [];

    transformedData.forEach((aiPersonData: AIPerson, idx: number) => {
      // 添加普通AI卡片
      cards.push(
        <div
          key={`ai-${aiPersonData.id}-${activeTab}-${i18n.language}`}
          data-card-index={idx}
          data-ai-id={aiPersonData.id}
          className="hover:shadow-lg transition-shadow duration-200 w-full"
          style={{
            aspectRatio: '9/16',
            width: '100%',
            height: 'auto',
          }}
        >
          <AiPersonCard
            content={aiPersonData}
            onClick={handleCardClick}
          />
        </div>
      );

      // 在第6个卡片后插入广告卡片（索引5后面）
      if (idx === 5) {
        cards.push(
          <div
            key={`promotion-card-${activeTab}-${i18n.language}`}
            className="hover:shadow-lg transition-shadow duration-200 w-full"
            style={{
              aspectRatio: '9/16',
              width: '100%',
              height: 'auto',
            }}
          >
            <PromotionCard />
          </div>
        );
      }
    });

    // 如果数据不足6个，在最后插入广告卡片
    if (transformedData.length < 6 && transformedData.length > 0) {
      cards.push(
        <div
          key={`promotion-card-last-${activeTab}-${i18n.language}`}
          className="hover:shadow-lg transition-shadow duration-200 w-full"
          style={{
            aspectRatio: '9/16',
            width: '100%',
            height: 'auto',
          }}
        >
          <PromotionCard />
        </div>
      );
    }

    return cards;
  }, [transformedData, activeTab, i18n.language, handleCardClick]);

  // 🚀 性能优化：使用useCallback缓存滚动函数
  const scrollToAiCard = useCallback((aiId: string) => {
    // 🔧 修复：清理之前的timeout
    if (scrollTimeoutRef.current) {
      clearTimeout(scrollTimeoutRef.current);
    }
    if (highlightTimeoutRef.current) {
      clearTimeout(highlightTimeoutRef.current);
    }

    // 延迟执行，确保DOM已渲染
    scrollTimeoutRef.current = setTimeout(() => {
      const cardElement = document.querySelector(`[data-ai-id="${aiId}"]`);
      if (cardElement) {
        // 计算滚动位置，让卡片居中显示
        const elementRect = cardElement.getBoundingClientRect();
        const absoluteElementTop = elementRect.top + window.pageYOffset;
        const middle = absoluteElementTop - (window.innerHeight / 2) + (elementRect.height / 2);

        window.scrollTo({
          top: Math.max(0, middle), // 确保不会滚动到负值
          behavior: 'smooth'
        });

        // 添加短暂的高亮效果
        cardElement.classList.add('highlight-card');
        highlightTimeoutRef.current = setTimeout(() => {
          cardElement.classList.remove('highlight-card');
          highlightTimeoutRef.current = null;
        }, 2000);

        // console.log('🎯 已滚动到AI角色:', aiId);
      } else {
        // console.warn('🔍 未找到AI角色卡片:', aiId);
        console.error('AI card not found', aiId);
      }
      scrollTimeoutRef.current = null;
    }, 300); // 延迟300ms确保渲染完成
  }, []);

  // 🚀 性能优化：使用useMemo缓存骨架屏数量，响应式布局统一数量
  const skeletonCount = useMemo(() => {
    return 6; // 响应式布局统一骨架屏数量，自动适配屏幕
  }, []);

  // 🚀 性能优化：使用useMemo缓存网格样式类名 - 固定列数响应式布局
  const gridClassName = useMemo(() => {
    return 'grid gap-3 sm:gap-4 md:gap-5 lg:gap-6 grid-cols-2 md:grid-cols-3 lg:grid-cols-4';
  }, []);

  // 响应式网格样式 - 使用 Tailwind CSS 类处理列数
  const gridStyle = useMemo(() => {
    return {}; // 使用 Tailwind CSS 类处理响应式布局
  }, []);

  // 延迟显示loading，避免闪烁问题
  useEffect(() => {
    let timer: NodeJS.Timeout;

    if (loading && data.length === 0) {
      // 如果正在加载且没有数据，延迟500ms显示loading
      timer = setTimeout(() => {
        setShowLoading(true);
      }, 500);
    } else {
      // 有数据或不在加载状态时，立即隐藏loading
      setShowLoading(false);
    }

    return () => {
      if (timer) {
        clearTimeout(timer);
      }
    };
  }, [loading, data.length]);

  // 检测从chat页面返回并自动滚动到对应位置
  useEffect(() => {
    // 只在非首次挂载且数据已加载完成时执行
    if (isFirstMount.current) {
      isFirstMount.current = false;
      return;
    }

    // 检查是否从chat页面返回
    const returnFromChat = sessionStorage.getItem('returnFromChat');
    const lastClickedAiId = sessionStorage.getItem('lastClickedAiId');

    if (returnFromChat === 'true' && lastClickedAiId && !loading && data.length > 0) {
      // console.log('🔄 检测到从chat页面返回，准备滚动到AI角色:', lastClickedAiId);

      // 清除标记，避免重复滚动
      sessionStorage.removeItem('returnFromChat');

      // 检查目标AI是否在当前数据中
      const targetAi = data.find(item => String(item.id) === lastClickedAiId);
      if (targetAi) {
        scrollToAiCard(lastClickedAiId);
      } else {
        // console.warn('🔍 目标AI角色不在当前页面数据中:', lastClickedAiId);
        console.error('target AI not found in current page data', lastClickedAiId);
        // 可以考虑加载更多数据或搜索该AI
      }
    }
  }, [data, loading]); // 依赖data和loading状态

  // 懒加载：使用 Intersection Observer 监听最后一张卡片
  useEffect(() => {
    if (!hasMore || loading || data.length === 0) return;
    // 获取最后一张卡片
    const lastCard = document.querySelector('[data-card-index="' + (data.length - 1) + '"]');
    if (!lastCard) return;

    const observer = new IntersectionObserver(
      (entries) => {
        const [entry] = entries;
        if (entry.isIntersecting) {
          setPage((prev: number) => {
            if (prev < totalPages) {
              return prev + 1;
            }
            return prev;
          });
        }
      },
      {
        rootMargin: '100px', // 提前100px触发
        threshold: 0.1, // 10%可见时触发
      }
    );

    observer.observe(lastCard);

    // 切换tab/语言后，内容高度不足时自动加载下一页
    const timer = setTimeout(() => {
      if (hasMore && !loading && page < totalPages && document.body.offsetHeight < window.innerHeight * 1.5) {
        setPage((prev: number) => {
          if (prev < totalPages) {
            return prev + 1;
          }
          return prev;
        });
      }
    }, 500);

    return () => {
      observer.disconnect();
      clearTimeout(timer);
    };
  }, [hasMore, loading, page, totalPages, data.length, activeTab, i18n.language, setPage]);

  // 🔧 新增：组件卸载时清理所有timeout，防止内存泄漏
  useEffect(() => {
    return () => {
      if (scrollTimeoutRef.current) {
        clearTimeout(scrollTimeoutRef.current);
        scrollTimeoutRef.current = null;
      }
      if (highlightTimeoutRef.current) {
        clearTimeout(highlightTimeoutRef.current);
        highlightTimeoutRef.current = null;
      }
    };
  }, []);

  return (
    <div className="w-full">
      <div className='w-[95%] md:w-[85%] lg:w-[80%] xl:w-[75%] m-auto'>
        {/* 存放副标题  */}
        <div
          className={`${isMobile ? 'text-[1.2rem] text-center' : 'text-[2rem]'} ${isMobile ? 'mt-[4rem]' : 'text-[2rem]'} font-bold my-2`}
          style={{ lineHeight: 1.3, fontFamily: dynamicFonts.font3 }}
        >
          <span dangerouslySetInnerHTML={{ __html: t(`home.subtitle.${activeTab}`) }} />
        </div>

        {/* 选项卡内容 */}
        <div className={`${isMobile ? 'pt-2' : 'pt-4'}`}>
          {/* 响应式网格布局 数据列表 - 完全响应式自动换行 */}
          <div className={gridClassName} style={gridStyle}>
            {/* Loading 状态渲染 - 延迟显示避免闪烁 */}
            {showLoading && (
              // 首次加载时显示加载骨架屏
              Array.from({ length: skeletonCount }).map((_, idx) => (
                <div
                  key={`loading-${idx}`}
                  className="w-full animate-pulse"
                  style={{
                    aspectRatio: '9/16',
                    minHeight: isMobile ? '240px' : '280px',
                    maxHeight: isMobile ? '400px' : '480px',
                  }}
                >
                  {/* 加载占位符 */}
                  <div className="bg-gray-300 dark:bg-gray-700 rounded-lg w-full h-full"></div>
                </div>
              ))
            )}

            {/* 无数据状态渲染 */}
            {!loading && !showLoading && data.length === 0 && (
              <div className="col-span-full flex flex-col items-center justify-center py-16 px-4">
                {/* 无数据图标 */}
                <div className="w-24 h-24 mb-4 text-gray-400 dark:text-gray-600">
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                    className="w-full h-full"
                  >
                    <path
                      d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"
                      fill="currentColor"
                      opacity="0.5"
                    />
                  </svg>
                </div>

                {/* 无数据文本 - 使用国际化 */}
                <p className="text-gray-500 dark:text-gray-400 text-lg font-medium text-center">
                  {t('home.noData')}
                </p>
              </div>
            )}

            {/* 数据列表渲染 - 🚀 性能优化：使用预转换的数据和广告卡片 */}
            {renderCards}
          </div>

          {/* 折叠面板区  */}
          <div className="mb-4 mt-16 md:mt-32">

            {/* 副标题  */}
            <div
              className={`${isMobile ? 'text-[1.2rem]' : 'text-[2rem]'} font-bold text-center mt-4 mb-8`}
              style={{ lineHeight: 1.3, fontFamily: dynamicFonts.font4 }}
            >
              <span dangerouslySetInnerHTML={{ __html: t(`home.QuestionsSubtitle.${activeTab}`) }} />
            </div>
            {activeTab === 'girl' && (
              <>
                <CollapsePanel title={t('home.collapse.girl.title')}>
                  {t('home.collapse.girl.content')}
                </CollapsePanel>
                <div className="h-2" />
                <CollapsePanel title={t('home.collapse.girl.title2')}>
                  {t('home.collapse.girl.content2')}
                </CollapsePanel>
                <div className="h-2" />
                <CollapsePanel title={t('home.collapse.girl.title3')}>
                  {t('home.collapse.girl.content3')}
                </CollapsePanel>
                <div className="h-2" />
                <CollapsePanel title={t('home.collapse.girl.title4')}>
                  {t('home.collapse.girl.content4')}
                </CollapsePanel>

              </>
            )}
            {activeTab === 'man' && (
              <>
                <CollapsePanel title={t('home.collapse.man.title')}>
                  {t('home.collapse.man.content')}
                </CollapsePanel>
                <div className="h-2" />
                <CollapsePanel title={t('home.collapse.man.title2')}>
                  {t('home.collapse.man.content2')}
                </CollapsePanel>
                <div className="h-2" />
                <CollapsePanel title={t('home.collapse.man.title3')}>
                  {t('home.collapse.man.content3')}
                </CollapsePanel>
                <div className="h-2" />
                <CollapsePanel title={t('home.collapse.man.title4')}>
                  {t('home.collapse.man.content4')}
                </CollapsePanel>
                <div className="h-2" />
                <CollapsePanel title={t('home.collapse.man.title5')}>
                  {t('home.collapse.man.content5')}
                </CollapsePanel>
              </>
            )}
            {activeTab === 'anime_girl' && (
              <>
                <CollapsePanel title={t('home.collapse.anime_girl.title')}>
                  <div>{t('home.collapse.anime_girl.content1_1')}</div>
                  <div className="mt-2">{t('home.collapse.anime_girl.contnet1_2')}</div>
                  <div className="mt-2">{t('home.collapse.anime_girl.contnet1_3')}</div>
                </CollapsePanel>
                <div className="h-2" />
                <CollapsePanel title={t('home.collapse.anime_girl.title2')}>
                  <div>{t('home.collapse.anime_girl.content2_1')}</div>
                  <div className="mt-2">{t('home.collapse.anime_girl.content2_2')}</div>
                </CollapsePanel>
                <div className="h-2" />
                <CollapsePanel title={t('home.collapse.anime_girl.title3')}>
                  <div>{t('home.collapse.anime_girl.content3_1')}</div>
                </CollapsePanel>
                <div className="h-2" />
                <CollapsePanel title={t('home.collapse.anime_girl.title4')}>
                  <div>{t('home.collapse.anime_girl.content4_1')}</div>
                  <div className="mt-2">{t('home.collapse.anime_girl.content4_2')}</div>
                  <div className="mt-2">{t('home.collapse.anime_girl.content4_3')}</div>
                </CollapsePanel>
                <div className="h-2" />
                <CollapsePanel title={t('home.collapse.anime_girl.title5')}>

                  <div className="mt-4 mb-2 text-white font-medium">{t('home.collapse.anime_girl.content5_1')}</div>

                  <ul className="list-none pl-2 space-y-4">
                    {(t('home.collapse.anime_girl.content5_1_list', { returnObjects: true }) as string[]).map((item, idx) => (
                      <li key={idx} className="pl-8 text-neutral-400 md:text-base text-sm font-medium leading-relaxed relative">
                        <div className="absolute left-0 top-0 w-6 h-6 bg-pink-600/20 rounded-full flex items-center justify-center">
                          <span className="text-pink-400 text-sm font-semibold">{idx + 1}</span>
                        </div>
                        {item}
                      </li>
                    ))}
                  </ul>
                </CollapsePanel>

              </>
            )}
            {activeTab === 'anime_man' && (
              <>
                <CollapsePanel title={t('home.collapse.anime_man.title')}>
                  <div>{t('home.collapse.anime_man.content1_1')}</div>
                  <div className="mt-2">{t('home.collapse.anime_man.contnet1_2')}</div>
                  <div className="mt-2">{t('home.collapse.anime_man.contnet1_3')}</div>
                </CollapsePanel>
                <div className="h-2" />
                <CollapsePanel title={t('home.collapse.anime_man.title2')}>
                  <div>{t('home.collapse.anime_man.content2_1')}</div>
                  <div className="mt-2">{t('home.collapse.anime_man.content2_2')}</div>
                </CollapsePanel>
                <div className="h-2" />
                <CollapsePanel title={t('home.collapse.anime_man.title3')}>
                  <div>{t('home.collapse.anime_man.content3_1')}</div>
                </CollapsePanel>
                <div className="h-2" />
                <CollapsePanel title={t('home.collapse.anime_man.title4')}>
                  <div>{t('home.collapse.anime_man.content4_1')}</div>
                </CollapsePanel>
                <div className="h-2" />
                <CollapsePanel title={t('home.collapse.anime_man.title5')}>
                  <div>{t('home.collapse.anime_man.content5_1')}</div>
                </CollapsePanel>
                <div className="h-2" />
                <CollapsePanel title={t('home.collapse.anime_man.title6')}>

                  <div className="mt-4 mb-2 text-white font-medium">{t('home.collapse.anime_man.content6_1')}</div>

                  <ul className="list-none pl-2 space-y-4">
                    {(t('home.collapse.anime_man.content6_1_list', { returnObjects: true }) as string[]).map((item, idx) => (
                      <li key={idx} className="pl-8 text-neutral-400 md:text-base text-sm font-medium leading-relaxed relative">
                        <div className="absolute left-0 top-0 w-6 h-6 bg-pink-600/20 rounded-full flex items-center justify-center">
                          <span className="text-pink-400 text-sm font-semibold">{idx + 1}</span>
                        </div>
                        {item}
                      </li>
                    ))}
                  </ul>
                </CollapsePanel>

              </>
            )}
          </div>

          {/* 富文本内容区  */}
          <div className="mt-[s8rem] md:mb-[2rem]">
            <TabRichContent tabKey={activeTab} />
          </div>
        </div>
      </div>

      {/* Registration Success Modal */}
      <RegistrationSuccessModal 
        show={showRegistrationSuccess} 
        onClose={handleCloseRegistrationModal} 
      />
    </div>
  )
} 